<?php
// +----------------------------------------------------------------------
// | Description: 客户
// +----------------------------------------------------------------------
// | Author:  Zl
// +----------------------------------------------------------------------
namespace app\crm\model;

use app\admin\model\CustomerBalanceChangeLog;
use app\admin\model\ShopModel;
use app\admin\model\CustomerBalance as CustomerBalanceModel;
use app\admin\model\ShopOrderModel;
use app\common\traits\ActionRecordTrait;
use app\mini\model\AdminUser;
use app\shop\model\AddOrderLog;
use app\shop\model\CustomerInfo;
use app\shop\model\Order;
use think\facade\Db;
use app\admin\model\Common;
use app\admin\model\ShopRefundOrderModel;
use think\response\Json;
use think\Validate;
use app\crm\logic\WhereLogic;
use app\crm\model\CustomerInfoAPI as CustomerInfoAPIModel;//引用EC接口文档

class Customer extends Common
{
    use ActionRecordTrait;
    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */
    protected $name = 'customer';

	public function shopRefundOrder()
	{
	    return $this->hasMany(ShopRefundOrderModel::class, 'uid','id');
	}

    public function nurse(){
        return $this->hasOne(ShopPerson::class,'id','nurse_id');
    }

    public function shop(){
        return $this->hasOne(ShopModel::class,'shop_id','shop_id');
    }

    public function amount(){
        return $this->hasMany(CustomerBalance::class, 'customer_id','id');
    }

    public function info(){
        return $this->hasOne(CustomerInfo::class, 'id','id');
    }

    public function account(){
        return $this->hasOne(CustomerAccount::class, 'id','id');
    }



    // 资产信息 - 获取用户余额
    public function getSurplusAccountCount($param)
    {
        if(empty($param['customer_id']))
        {
            $this->error = "缺少必传参数用户ID";
            return false;
        }
        $list = [];
        // 账户总额
        $account = Db::name('customer_account')->where('id',$param['customer_id'])->find();
        // 本金
        $list['balance'] = $account['balance'] ?? 0;
        // 赠金
        $list['gift'] = $account['gift'] ?? 0;
        // 本金+赠金
        if (is_array($account) && isset($account['balance'], $account['gift']))
        {
            $list['all'] = bcadd((string)$account['balance'],(string)$account['gift'],2);
        } else {
            $list['all'] = 0;
        }
        // 积分
        $list['point'] = $account['point'] ?? 0;
        // 卡项
        $list['service'] = Db::name('service')
            ->where('customer_id',$param['customer_id'])
            ->where('status' , 1)
            ->count() ?? 0;
        // 优惠券
        $currentTime = time(); // 获取当前时间戳
        $list['coupon'] = Db::name('coupon_provide_customer')
            ->where('customer_id', $param['customer_id'])
            ->where('staus', '<>', 1) // 排除已使用的优惠券
            ->where(function($query) use ($currentTime) {
                // 处理结束时间逻辑
                $query->where(function($sub) use ($currentTime) {
                    // 情况1：有结束时间且未过期
                    $sub->whereNotNull('end_time')
                        ->where('end_time', '>', $currentTime);
                })->whereOr(function($sub) {
                    // 情况2：没有结束时间（永久有效）
                    $sub->whereNull('end_time');
                });
            })
            ->count();
        return $list;
    }


    // 获取客户的余额
    public function getCustomerBalance($customer_id,$business_type){

        $balanceList = Db::name('customer_balance')
            ->where([['customer_id','=',$customer_id]])
            ->column('money,complimentary_money,shop_transfer_money','balance_category_id');
        $money               = $balanceList[$business_type]['money'] ?? 0; // 获取用户余额
        $complimentary_money = $balanceList[$business_type]['complimentary_money'] ?? 0; // 获取用户赠金
        $shop_transfer_money = $balanceList[$business_type]['shop_transfer_money'] ?? 0; // 获取店转金额

        return ['money'=>$money,'complimentary_money'=>$complimentary_money,'shop_transfer_money'=>$shop_transfer_money];
    }

	public function swipeCustomerData(){
	    //客户分类 73是A类 72是B类 71是C类 70是D类
	    $customer_type = 73;
	    $data = self::with(['shopRefundOrder' => function($query){
	            $query->field('id,uid,deal_time,type,refund_type,is_pay,status,pay_amount');
	            $query->where('type',3);
	            $query->where('refund_type','<>','101.03');
	            $query->where('is_pay',1);
	            $query->where('status',2);
	            $query->where('pay_amount','>=',500);
	            $query->order('deal_time');
	            //$query->limit(2);
	        }])->where('cj_money',0)->where('member_classification',$customer_type)->field('id,customer_name')->limit(10000000)->select()->toArray();
	        echo count($data);die;
	        foreach($data as $key=>$v){
	            if(isset($v['shopRefundOrder'][0])){
	                $update=[];
	                $update['cj_time'] = $v['shopRefundOrder'][0]['dealTime'];
	                $update['cj_money'] = $v['shopRefundOrder'][0]['payAmount'];
	                $update['cj_order_id'] = $v['shopRefundOrder'][0]['id'];

	                self::where('id',$v['id'])->update($update);
	            }
	        }

	}

    //获取客户的消耗金额
    public function getCustomerAmountConsumed($customerBalance=[]){

        $money = $customerBalance['money'];  //客户的本金余额

        $complimentary_money =  $customerBalance['complimentary_money']; //客户的赠金余额

        $actual_order_amout = $customerBalance ['actual_order_amout'];//订单的金额

        $pay_zj_amount = $pay_bj_amount = 0.00; //消耗的赠金、本金

        if($complimentary_money <= 0 ) {
            $pay_bj_amount = $actual_order_amout;
        }else{
            $bj_zj_add = bcadd($complimentary_money,$money,2); //本金+赠金的和
            $need_pay_zj_amount = bcmul(bcdiv($complimentary_money,$bj_zj_add,2),$actual_order_amout,2);//需要支付的赠金
            $need_pay_bj_amount  = bcsub($actual_order_amout,$need_pay_zj_amount,2); //需要支付的本金
            if($complimentary_money >0 ){
                $pay_zj_amount_diff = 0;
                if($complimentary_money >= $need_pay_zj_amount ){
                    $pay_zj_amount = $need_pay_zj_amount; //实际要支付的赠金
                }else{
                    $pay_zj_amount_diff = bcsub($need_pay_zj_amount,$complimentary_money,2);
                    $pay_zj_amount = $complimentary_money; //实际要支付的赠金
                }
                $pay_bj_amount =  bcadd($need_pay_bj_amount,$pay_zj_amount_diff,2); //实际要支付的本金
            }
        }

        return ['pay_zengjin_amount'=>$pay_zj_amount,'pay_benjin_amount'=>$pay_bj_amount];
    }


    /**
     * 设置客户的年龄
     */
    public function setCustomerAge(): bool
    {
        $field = 'id,birthday';
        // try {
            //处理更新的数据
            $list  = $this -> field($field) -> select() -> toArray();
            $saveAll = array();
            foreach($list as $key => $val){
                if ($val['birthday']) {
                    $setData            = array();
                    $setData['age']     = bcsub(date('Y'),date('Y',$val['birthday']));
                    $setData['id']      = $val['id'];
                    $saveAll[]          = $setData;
                }
            }

            if($saveAll){
                // print_r($setData);exit;
                $res = $this -> saveAll($saveAll);
                if ($res === false) {
                   $this->error = '更新失败';
                   return array();
                }
            }
        // } catch (\Exception $e) {
        //     $this->error = '更新失败2';
        //     return false;
        // }
        return true;
    }


    /* 预存货列表
    * @param  array $request 请求参数
    * @return array
    */
    public function prestockList(array $request):array
    {
        $paging['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
        $paging['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
        $is_page= isset($request['is_page']) && intval($request['is_page']) ? intval($request['is_page']) : 1;

        $customer_id = $request['uid']??0;

        $map = [
            ['customer_id','=',$customer_id],
            ['num','>',0],
            ['is_cancel','=',0]
        ];

        $goodsList = CustomerPrestockGoods::with([
            'shop'=>function($query)use($map){
                $query->field('shop_id,shop_name,market_name');
            },
            'shopordergoods'=>function($query)use($map){
                $query->field('id,goods_name,kingdee_code,spec_name,pay_price,number,prestock_type,takeout_stock_num');
            },
            'customer'=>function($query)use($map){
                $query->field('id,customer_name');
            },
            'shipmentlog'=>function($query)use($map){
                $query->field('num,c_prestock_goods_id');
            }
        ]);
        $count = $goodsList->where($map)->count();
        $business_type = [
            1=>'疤痕', 2=>'项目', 3=>'青春痘', 4=>'护肤品',0=>'无'
        ];
        if($count>0){
            if($is_page == 1){
                $goodsList = $goodsList->where($map)
                    ->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit'])
                    ->order('id','desc')->select()
                    ->toArray();
            }else{
                $goodsList = $goodsList->where($map)
                    ->order('id','desc')->select()
                    ->toArray();
            }
            foreach($goodsList as $k=>&$v){
                $v['market_name'] = !empty($v['shop'])?$v['shop']['marketName']:'';
                $v['shop_name'] = !empty($v['shop'])?$v['shop']['shopName']:'';
                $v['customer_name'] = !empty($v['customer'])?$v['customer']['customer_name']:'';
                $v['business_type'] = isset($business_type[$v['business_type']]) ?$business_type[$v['business_type']]:'';
                $v['spec_name'] = '';
                $v['sales_amount'] = 0.00;
                $v['prestock_num'] = 0;
                $goods_name = '';
                $pay_price = 0.00;
                if(!empty($v['shopordergoods'])){
                    $goods_name = $v['shopordergoods']['goods_name']."--".$v['shopordergoods']['kingdee_code'];
                    $v['spec_name'] = $v['shopordergoods']['spec_name']; //商品规格
                    $v['sales_amount'] = bcmul($v['shopordergoods']['takeout_stock_num'],$v['shopordergoods']['pay_price'],2); //总的预存销售金额
                    $v['prestock_num'] =  $v['shopordergoods']['takeout_stock_num']; //总预存数量
                    $pay_price = $v['shopordergoods']['pay_price'];
                }
                $v['residual_shipment_num'] = $v['num']; // 剩余预存数量

                $shipment_num = 0;
                if(!empty($v['shipmentlog'])){
                    $actual_shipment_num = array_column($v['shipmentlog'],'num');
                    $actual_shipment_num =  array_sum($actual_shipment_num);
                    $shipment_num = bcadd($actual_shipment_num,$shipment_num,2);
                }
                $v['shipment_num'] = $shipment_num;  //出货数量
                $v['residual_sales_amount'] = bcmul($pay_price,$v['num'],2);
                $v['goods_name'] = $goods_name;
            }

        }
        $data              = [];
        $data['list']      = $goodsList ?? [];
        $data['dataCount'] = $count ?? 0;
        return $data;
    }


    /**
     * 列表
     * @param  array $request 请求参数
     * @return bool
     */
    public function getDataList(array $param): array
    {
        $page = $param['page'] ?? 1;
        $pagesize = $param['pagesize'] ?? 10;
        $where = [];
        //录入时间
        if(!empty($param['create_time_start']) || !empty($param['create_time_end']))
        {
            if(!empty($param['create_time_start']))
            {
                $start = strtotime($param['create_time_start'].'00:00:00');

            }else
            {
                $start = strtotime(time().'00:00:00');
            }
            if(!empty($param['create_time_end']))
            {
                $over = strtotime($param['create_time_end'].'23:59:59');
            }else
            {
                $over = strtotime(time().'23:59:59');
            }
            $where[] = ['c.create_time','between',[$start, $over]];
        }
        //姓名/K3码
        if(!empty($param['customer_name']))
        {
            if(preg_match('/^\d+\.\d+\.\d+$/', $param['customer_name']))
            {
                $where[] = ['c.king_no','=',$param['customer_name']];
            }else
            {
                $where[] = ['c.customer_name','like','%'.$param['customer_name'].'%'];
            }
        }
        //电话
        if(!empty($param['telephone']))
        {
            $where[] = ['c.telephone','=',$param['telephone']];
        }
        //年龄
        if(!empty($param['agemin']))
        {
            $where[] = ['c.age','>=',$param['agemin']];
        }
        // 是否中台转店
        if(isset($param['is_transfer']))
        {
            $where[] = ['c.is_transfer','=',$param['is_transfer']];
        }
        if(!empty($param['agemax']))
        {
            $where[] = ['c.age','<=',$param['agemax']];
        }
        //顾客来源
        if(!empty($param['source_id']))
        {
            $where[] = ['c.source_id','=',$param['source_id']];
        }
        //客服- 添加人
        if(!empty($param['customer_service_name']))
        {
            $where[] = ['a.realname','=',$param['customer_service_name']];
        }
        //会员等级
        if(!empty($param['membership_leve']))
        {
            $where[] = ['c.membership_leve','=',$param['membership_leve']];
        }
        //市场
        if(!empty($param['market_id']))
        {
            $where[] = ['s.market_id','=',$param['market_id']];
        }
        //门店类型
        if(!empty($param['shop_id']))
        {
            $where[] = ['c.shop_id','=',$param['shop_id']];
        }
        //门店类型
        if(!empty($param['type']))
        {
            $where[] = ['s.type','=',$param['type']];
        }
        //主治医师
        if(!empty($param['doctor_id']))
        {
            $where[] = ['c.doctor_id','=',$param['doctor_id']];
        }
        //护理师
        if(!empty($param['nurse_id']))
        {
            $where[] = ['c.nurse_id','=',$param['nurse_id']];
        }
        //咨询师
        if(!empty($param['developers']))
        {
            $where[] = ['c.developers','=',$param['developers']];
        }
        //修复进展
        if(!empty($param['repair_progress']))
        {
            $where[] = ['c.repair_progress','=',$param['repair_progress']];
        }
        //治疗科室
        if(!empty($param['department']))
        {
            $where[] = ['c.department','=',$param['department']];
        }
        //品项搜索
        if(!empty($param['item_type']))
        {
            $where[] = ['c.item_type','like','%'.implode(',',$param['item_type']).'%'];
        }
        //到店类型
        if(!empty($param['type_store']))
        {
            $where[] = ['i.type_store','=',$param['type_store']];
        }
        //累计消费金额
        if(isset($param['consumption_min']) && is_numeric($param['consumption_min']))
        {
            $where[] = ['consumption', '>=', $param['consumption_min']];
        }
        //累计消费金额
        if(isset($param['consumption_max']) && is_numeric($param['consumption_max']))
        {
            $where[] = ['consumption', '<=', $param['consumption_max']];
        }
        // 类型时间搜索
        if(!empty($param['time_type']))
        {
            $timeFieldMap = [
                1 => 'one_time',   // 初诊
                2 => 'two_time',   // 复诊
                3 => 'three_time', // 消费
                4 => 'four_time',  // 诊疗
                5 => 'five_time'   // 其他
            ];
            // 获取对应的时间字段名
            $timeField = $timeFieldMap[$param['time_type']] ?? null;
        }
        if (!empty($param['start_time']) || !empty($param['end_time']))
        {
            // 确定使用的时间字段
            $searchField = $timeField ?? 'one_time';

            if(!empty($param['start_time']))
            {
                $start_time = $param['start_time'].'00:00:00';
            }else
            {
                $start_time = time().'00:00:00';
            }
            if(!empty($param['end_time']))
            {
                $end_time = $param['end_time'].'23:59:59';
            }else
            {
                $end_time = time().'23:59:59';
            }
            // 添加时间范围条件
            $where[] = ["i.$searchField", 'between', [$start_time, $end_time]];
        }
        //
        if(!empty($param['export']) && $param['export'] == 1)
        {
            $list['data'] =  $this->field('c.*, i.*, a.realname as operator_name, s.shop_name, s.market_name, p.name as developers_name')
            ->order('c.id','DESC')
            ->alias('c')
            ->leftJoin('admin_user a','c.operator = a.id') // 添加人
            ->leftJoin('shop s','c.shop_id = s.shop_id')   // 店铺
            ->leftJoin('customer_info i','c.id = i.id')   // 用户其他信息
            ->leftJoin('shop_person p','c.developers = p.id')   // 咨询师
            ->where($where)
            ->select();
        }else
        {
            $res =  $this->field('c.*, i.*, a.realname as operator_name, s.shop_name, s.market_name, p.name as developers_name')
            ->order('c.id','DESC')
            ->alias('c')
            ->leftJoin('admin_user a','c.operator = a.id') // 添加人
            ->leftJoin('shop s','c.shop_id = s.shop_id')   // 店铺
            ->leftJoin('customer_info i','c.id = i.id')   // 用户其他信息
            ->leftJoin('shop_person p','c.developers = p.id')   // 咨询师
            ->where($where)
            ->paginate([
                'list_rows'=>$pagesize,
                'page'=>$page,
                'query'=>request()->param()
            ]);
            $list = [];
            $list = json_decode(json_encode($res),true);
        }



        if(!empty($list))
        {
            foreach($list['data'] as &$item)
            {
                // 咨询项目
                if (!empty($item['item_type']))
                {
                    // 解析 JSON 数组
                    $itemTypes = json_decode($item['item_type'], true);
                    $itemNames = [];

                    foreach ($itemTypes as $typeIds)
                    {
                        $names = [];

                        // 遍历三级类目ID (例如: [1,4,26])
                        foreach ($typeIds as $id)
                        {
                            // 查询对应的类目名称
                            $category = DB::table('xy_item_type')
                                ->where('id', $id)
                                ->value('name');
                            $names[] = $category ?: ''; // 若未找到，使用空字符串
                        }
                        $itemNames[] = $names;
                    }
                    // 添加到当前记录
                    $item['item_names'] = $itemNames;
                }

                // 会员等级
                if($item['membership_leve'] == 1)
                {
                    $item['membership_leve_name'] = '白玉兰';
                }elseif($item['membership_leve'] == 2)
                {
                    $item['membership_leve_name'] = '紫玉兰';
                }elseif($item['membership_leve'] == 3)
                {
                    $item['membership_leve_name'] = '金玉兰';
                }else
                {
                    $item['membership_leve_name'] = '暂无';
                }
//                $item['type_store'] = 1;
                // 到店类型
                if($item['type_store'] == 1)
                {
                    $item['type_store_name'] = '首诊';
                }elseif($item['type_store'] == 2)
                {
                    $item['type_store_name'] = '复诊';
                }elseif($item['type_store'] == 3)
                {
                    $item['type_store_name'] = '再消费';
                }elseif($item['type_store'] == 4)
                {
                    $item['type_store_name'] = '诊疗';
                }elseif($item['type_store'] == 5)
                {
                    $item['type_store_name'] = '其他';
                }else
                {
                    $item['type_store_name'] = '暂无';
                }
                // 来源 + 修复进展
                $item['repair_progress_name'] = Db::name('setting')->where('id',$item['repair_progress'])->value('name');
                $item['source_name'] = Db::name('setting')->where('id',$item['source_id'])->value('name');
                // 主治医师 + 护理师
                $item['doctor_name'] = Db::name('shop_person')->where('id',$item['doctor_id'])->value('name');
                $item['nurse_name'] = Db::name('shop_person')->where('id',$item['nurse_id'])->value('name');
                $item['duty_nures_name'] = Db::name('shop_person')->where('id',$item['duty_nures_id'])->value('name');
                // 生日
                $item['birthday'] = ($item['birthday'] == 0 || $item['birthday'] == -28800) ? '' : date('Y-m-d', $item['birthday']);
                // 性别
                switch ($item['sex']) {
                    case 1: $item['sex'] = '男'; break;
                    case 2: $item['sex'] = '女'; break;
                    default: $item['sex'] = '未知';
                }
                // 治疗科室
                $item['department'] = $item['department'] == 1 ? '疤痕科' : '医美科';
                // 是否中台转店
                $item['is_transfer'] = $item['is_transfer'] == 0 ? '否' : '是';
                // 转店处理状态
                $statusMap = [
                    0 => '无需处理',
                    1 => '待处理',
                    2 => '已处理'
                ];
                $item['turn_status'] = $statusMap[$item['turn_status']] ?? '未知状态';
                //咨询项目
                if (!empty($item['item_names']))
                {
                    $arrays = [];
                    // 遍历每个子数组
                    foreach ($item['item_names'] as $subArray)
                    {
                        // 子数组内元素用斜杠拼接，并添加中括号
                        $arrays[] = '[' . implode("-", $subArray) . ']';
                    }
                    // 不同数组之间用逗号拼接
                    $item['item_names_str'] = implode(',', $arrays);
                }else
                {
                    $item['item_names_str'] = '';
                }
            }
            unset($item); // 释放引用
        }

        return $list;
    }



    /* 详情
    * @param  array $request 请求参数
    * @return array
    */
    public function getDataInfo(array $request): array
    {
        $customerId = $request['id'];

        $list = [];
        $list =  $this->field('c.*, i.*, s.shop_name, a.realname as operator_name, s.market_name')
        ->alias('c')
        ->leftJoin('admin_user a','c.operator = a.id') // 添加人
        ->leftJoin('shop s','c.shop_id = s.shop_id')   // 店铺
        ->leftJoin('customer_info i','c.id = i.id')   // 顾客其他信息
        ->where('c.id',$customerId)
        ->find();
        if(!empty($list))
        {
            $list = json_decode(json_encode($list),true);
            // 咨询项目
            if (!empty($list['item_type']))
            {
                // 解析 JSON 数组
                $itemTypes = json_decode($list['item_type'], true);
                $itemNames = [];

                foreach ($itemTypes as $typeIds)
                {
                    $names = [];

                    // 遍历三级类目ID (例如: [1,4,26])
                    foreach ($typeIds as $id)
                    {
                        // 查询对应的类目名称
                        $category = DB::table('xy_item_type')
                            ->where('id', $id)
                            ->value('name');
                        $names[] = $category ?: ''; // 若未找到，使用空字符串
                    }
                    $itemNames[] = $names;
                }
                // 添加到当前记录
                $list['item_names'] = $itemNames;
            }

            // 会员等级
            if($list['membership_leve'] == 1)
            {
                $list['membership_leve_name'] = '白玉兰';
            }elseif($list['membership_leve'] == 2)
            {
                $list['membership_leve_name'] = '紫玉兰';
            }elseif($list['membership_leve'] == 3)
            {
                $list['membership_leve_name'] = '金玉兰';
            }else
            {
                $list['membership_leve_name'] = '非会员';
            }
//            $list['type_store'] = 1;
            // 到店类型
            if($list['type_store'] == 1)
            {
                $list['type_store_name'] = '首诊';
            }elseif($list['type_store'] == 2)
            {
                $list['type_store_name'] = '复诊';
            }elseif($list['type_store'] == 3)
            {
                $list['type_store_name'] = '再消费';
            }elseif($list['type_store'] == 4)
            {
                $list['type_store_name'] = '诊疗';
            }elseif($list['type_store'] == 5)
            {
                $list['type_store_name'] = '其他';
            }else
            {
                $list['type_store_name'] = '暂无';
            }
            $list['birthday'] = date('Y-m-d',$list['birthday']);

            // 客户分类 - 滚动一年消费

            // 最近到院 - 订单OR核销最新时间
            $shopOrderTime = ShopOrderModel::where('uid',$customerId)->where('status',2)->field('deal_time')->order('deal_time','desc')->find();
            $consumption_time = !empty($shopOrderTime)?$shopOrderTime['deal_time']:0;
            $order_time = ShopRefundOrderModel::where('uid',$customerId)->where('status',2)->field('deal_time')->order('deal_time','desc')->find();
            $consumption_times = !empty($order_time)?$order_time['deal_time']:0;
            $service_log = ServiceLog::where('customer_id',$customerId)->where('is_cancel',0)->order('create_time','desc')->find();
            $service_time = !empty($service_log)?strtotime($service_log['create_time']):0;
            $last_enter_time  = array($consumption_time,$consumption_times,$service_time);

            rsort($last_enter_time);

            $list['last_time'] = !empty($last_enter_time[0])?date('Y-m-d',$last_enter_time[0]):'';

            // 来源 + 修复进展
            $list['repair_progress_name'] = Db::name('setting')->where('id',$list['repair_progress'])->value('name');
            $list['source_name'] = Db::name('setting')->where('id',$list['source_id'])->value('name');

            // 主治医师 + 护理师
            $list['doctor_name'] = Db::name('shop_person')->where('id',$list['doctor_id'])->value('name');
            $list['nurse_name'] = Db::name('shop_person')->where('id',$list['nurse_id'])->value('name');

            $list['duty_nures_name'] = Db::name('shop_person')->where('id',$list['duty_nures_id'])->value('name');

            //累计消费
            $account = CustomerAccount::find($customerId);
            $list['all_money'] = $account['all_balance'];
            //归属客服
            $list['operator'] = $list['operator_name'];
            $list['doctor_id'] = !empty($list['doctor_id'])?$list['doctor_id']:'';
            $list['nurse_id']  = !empty($list['nurse_id'])?$list['nurse_id']:'';
            $list['developers']  = !empty($list['developers'])?$list['developers']:'';
            $list['duty_nures_id']  = !empty($list['duty_nures_id'])?$list['duty_nures_id']:'';

            $list['progress']  = !empty($list['progress'])?$list['progress']:'';
            $list['introducer']  = !empty($list['introducer'])?$list['introducer']:'';
            $list['department']  = !empty($list['department'])?$list['department']:'';
            $list['repair_progress']  = !empty($list['repair_progress'])?$list['repair_progress']:'';


        }
        return $list;
    }


    /**
     * 添加
     * @param  array $request 请求参数
     * @return bool
     */
    public function addData(array $request): bool
    {
        // 定义必填字段及其中文名称
        $requiredFields = [
            'shop_id' => '所属店铺',
            'customer_name' => '姓名',
            'telephone' => '手机号',
            'source_id' => '顾客来源',
            'operator' => '创建人ID',
        ];
        foreach ($requiredFields as $field => $name)
        {
            if (!array_key_exists($field, $request))
            {
                $this->error = "{$name}不能为空";
                return false;
            }
        }

        // 手机号格式
         $checkP = '/^1(3[0-9]|4[0-9]|5[0-9]|6[0-9]|7[0-9]|8[0-9]|9[0-9])\d{8}$/';
        if(!preg_match($checkP, $request['telephone']))
        {
            $this->error = "手机号码格式不正确";
            return false;
        }

        // 店铺判断
        $shop = Db::name('shop')->where('shop_id',$request['shop_id'])->where('status',1)->count();
        if($shop == 0)
        {
            $this->error = "该店铺不存在或者已经关闭";
            return false;
        }

        // 入库前判断数据
        $check = Db::name('customer')->where('telephone',$request['telephone'])->count();
        if($check > 0)
        {
            $this->error = "该手机号已存在";
            return false;
        }

        //处理用户年龄
        $request['age'] = '';
        if (!empty($request['birthday']))
        {
		   $request['age'] = bcsub(date('Y'),date('Y',strtotime($request['birthday'])));
        }else
        {
            $request['age'] = '';
        }






        //时间类型
        $request['create_time'] = time();
        $request['birthday'] = strtotime($request['birthday']);
        $request['is_show_balance'] = 1; // 小程序显示余额，0 否 1 是
        $request['card_is_correct'] = 1; // 卡项是否正确 0否 1是 (选择是后无法修改)
        $request['item_type'] = json_encode($request['item_type']);

        // 顾客其他信息
        if(isset($request['type_store']))
        {
            $customer_info['type_store'] = $request['type_store'];
            $current_time = date('Y-m-d H:i:s');
            switch ($customer_info['type_store'])
            {
                case 1: // 初诊
                    $customer_info['one_time'] = $current_time;
                    break;
                case 2: // 复诊
                    $customer_info['two_time'] = $current_time;
                    break;
                case 3: // 再消费
                    $customer_info['three_time'] = $current_time;
                    break;
                case 4: // 诊疗
                    $customer_info['four_time'] = $current_time;
                    break;
                case 5: // 其他
                    $customer_info['five_time'] = $current_time;
                    break;
            }
            unset($request['type_store']);
        }

        try {
            Db::startTrans();

            $customerId = $this->insertGetId($request);

            if(!$customerId)
            {
                $this->error = '添加失败';
                return false;
            }

            // 存储客户的余额信息 - 默认都为0
            $customer_account['id'] =$customerId;
            $check_account = Db::name('customer_account')->where('id',$customerId)->count();
            if($check_account < 1)
            {
                Db::name('customer_account')->insert($customer_account);
            }

            // 存储客户的其他信息
            $customer_info['id'] =$customerId;
            $check_info = Db::name('customer_info')->where('id',$customerId)->count();
            if($check_info < 1)
            {
                Db::name('customer_info')->insert($customer_info);
            }

            //查询商城是否有该用户信息


            Db::commit();

            $this->error = '添加成功';
            return true;

        } catch (Exception $e)
        {
            Db::rollback();
            $this->error = $e->getMessage() ?: '添加失败';
            return false;
        }
    }


    // /**
    //  * 编辑
    //  * @param  array $request 请求参数
    //  * @return bool
    //  */
    public function saveData(array $request): bool
    {
        if(empty($request['id']))
        {
            $this->error = "缺少必传参数用户ID";
            return false;
        }
        $info = $this->where('id',$request['id'])->find();
         // 手机号格式验证
         if(!empty($request['telephone']))
         {
            $checkP = '/^1(3[0-9]|4[0-9]|5[0-9]|6[0-9]|7[0-9]|8[0-9]|9[0-9])\d{8}$/';
            if (!preg_match($checkP, $request['telephone']))
            {
                $this->error = "手机号码格式不正确";
                return false;
            }

            // 手机号唯一性验证（排除当前用户）
            $customerExists = Db::name('customer')
                ->where('telephone', $request['telephone'])
                ->where('id', '<>', $request['id']) // 排除当前修改的用户
                ->count();

            if ($customerExists > 0)
            {
                $this->error = "该手机号已被其他用户使用";
                return false;
            }

            //如果修改了手机号
            if($request['telephone'] != $info['telephone'])
            {
                //手机号变更记录
                $insert = [
                    'last_customer_phone'=>$info['telephone'],
                    'telephone'=>$request['telephone'],
                    'customer_id'=>$request['id'],
                    'operator_id'=>$request['user_id'],
                    'create_time'=>time(),
                ];
                DB::name('customer_info_change_log')->insert($insert);

                //累计消费数字化
                $shop_type = DB::name('shop')->where('shop_id',$info['shop_id'])->value('shop_type');
                $shop_ids = DB::name('shop')->where('shop_type',$shop_type)->column('shop_id');
                $update = [
                    'customer_phone'=>$request['telephone'],
                    'update_time'=>time(),
                ];
                DB::name('customer_consumption_log')->whereIn('shop_id',$shop_ids)->where('customer_phone',$info['telephone'])->update($update);


                //修改手机号到商城小程序
                if(!empty($request['mini_id']))
                {
                    $queryParams = [
                            'uid' => $request['mini_id'],
                            'phone' => $request['telephone']
                    ];
                    $queryString = http_build_query($queryParams);

                    $url = env('SHOP.shop_url').'/api/crm/user_phone?'.$queryString;
                    $apiResponse = $this->callApi($url);
                    if ($apiResponse)
                    {
                        $data = json_decode($apiResponse, true);
                        if($data['status'] != 200)
                        {
                            return false;
                        }
                    }
                }
            }
         }
         //如果是转店补充了资料
         if($info['is_transfer'] == 1 && empty($info['item_type']) && !empty($request['item_type']))
         {
             $request['is_transfer'] = 2;
         }


         //如果修改了主治医师和所属护士
         if(!empty($request['doctor_id']) &&  $request['doctor_id'] != $info['doctor_id'] && !empty($info['doctor_id']))
         {
            // 记录日志
            $d_log = [
                'shop_id' => $request['shop_id'],
                'customer_id' => $request['id'],
                'type' => 1,
                'last' => $info['doctor_id'],
                'now' => $request['doctor_id'],
                'operator_id' => $request['user_id'],
                'create_time' => time()
            ];
            DB::name('customer_change_log')->insert($d_log);
         }


         //如果修改了主治医师和所属护士
         if(!empty($request['nurse_id']) &&  $request['nurse_id'] != $info['nurse_id'] && !empty($info['nurse_id']))
         {
            $n_log = [
                'shop_id' => $request['shop_id'],
                'customer_id' => $request['id'],
                'type' => 2,
                'last' => $info['nurse_id'],
                'now' => $request['nurse_id'],
                'operator_id' => $request['user_id'],
                'create_time' => time()
            ];
            DB::name('customer_change_log')->insert($n_log);
         }

        //处理年龄和生日
        if(!empty($request['birthday'])){
            $request['age'] = $this->calculateAge($request['birthday']);
            $request['birthday'] = strtotime($request['birthday']);
        }
        //处理介绍人-客户的id
        if(!empty($request['introducer'])){
            if($request['introducer'] == $request['id'] ){
                $this->error = "该介绍人不能为自己";
                return false;
            }
            // 判断介绍人是否存在
            $customerExists = Db::name('customer')
                ->where('id', $request['introducer'])
                ->where('id', '<>', $request['id']) // 排除当前修改的用户
                ->count();
            if ($customerExists <= 0) {
                $this->error = "该介绍人不存在";
                return false;
            }

        }
        // 更新时间字段（不再更新创建时间和首次到店时间）
        $request['update_time'] = time(); // 新增更新时间
        if(!empty($request['item_type']))
        {
            $request['item_type'] = json_encode($request['item_type']); // 保持JSON编码
        }
        $customer_info =[];
        // 顾客其他信息
        if(!empty($request['type_store']))
        {
            $customer_data = Db::name('customer_info')->where('id',$request['id'])->find();


            $type_store = $request['type_store'];
            if($type_store != $customer_data['type_store'])
            {

                $current_time = date('Y-m-d H:i:s');


                //初诊
                if(empty($customer_data['one_time']) && $type_store == 1){
                    $customer_info['one_time'] = $current_time;
                    $customer_info['type_store'] = $type_store;
                }
                //复诊
                if(!empty($customer_data['one_time']) && $type_store == 2 && empty($customer_data['two_time']) ){
                    $customer_info['two_time'] = $current_time;
                    $customer_info['type_store'] = $type_store;
                }
                //再消费
                if(!empty($customer_data['one_time']) && !empty($customer_data['two_time']) &&  $type_store == 3 && empty($customer_data['three_time'])  ){
                    $customer_info['three_time'] = $current_time;
                    $customer_info['type_store'] = $type_store;
                }

                //诊疗
                if(!empty($customer_data['one_time']) && !empty($customer_data['two_time']) &&  !empty($customer_data['three_time']) &&  $type_store == 4 && empty($customer_data['four_time'])  ){
                    $customer_info['four_time'] = $current_time;
                    $customer_info['type_store'] = $type_store;
                }
                //其他
                if(!empty($customer_data['one_time']) && !empty($customer_data['two_time']) && !empty($customer_data['three_time']) &&  !empty($customer_data['four_time']) && $type_store == 5 && empty($customer_data['five_time'])  ){
                    $customer_info['five_time'] = $current_time;
                    $customer_info['type_store'] = $type_store;
                }



//                switch ($customer_info['type_store'])
//                {
//                    case 1: // 初诊
//                        $customer_info['one_time'] = $current_time;
//                        break;
//                    case 2: // 复诊
//                        $customer_info['two_time'] = $current_time;
//                        break;
//                    case 3: // 再消费
//                        $customer_info['three_time'] = $current_time;
//                        break;
//                    case 4: // 诊疗
//                        $customer_info['four_time'] = $current_time;
//                        break;
//                    case 5: // 其他
//                        $customer_info['five_time'] = $current_time;
//                        break;
//                }
            }
            unset($request['type_store']);
        }


        try {
            Db::startTrans();

            unset($request['user_id']);
            unset($request['operator']);

            // 更新操作（替换原来的插入）
            $updateResult = Db::name('customer')
                ->where('id', $request['id'])
                ->update($request);
            $updateInfo = true;
            if(!empty($customer_info)){
                $updateInfo = Db::name('customer_info')->where('id',$request['id'])->update($customer_info);
            }

            if ($updateResult === false || $updateInfo === false)
            {
                $this->error = '更新失败';
                return false;
            }

            Db::commit();
            $this->error = '更新成功';
            return true;

        } catch (Exception $e) {
            Db::rollback();
            $this->error = $e->getMessage() ?: '更新失败';
            return false;
        }
    }

    //获取顾客年龄
    public   function calculateAge($birthday) {
        $currentDate = date('Y-m-d');
        $birthdayDate = date('Y-m-d', strtotime($birthday));
        $age = date_diff(date_create($currentDate), date_create($birthdayDate))->y;
        return $age;
    }



    private function callApi($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'cURL Error: '. curl_error($curl);
            return false;
        }
        curl_close($curl);
        return $response;
    }


    /**
     * 更新进店时间
     * 更新转店状态
     */
    public function setCustomerStatus(array $request)
    {
        try {
            if (isset($request['customer_id']) && intval($request['customer_id']) <= 0) {
                // code...
                $this->error = '请选择需要设置的客户';
                return false;
            }
            $customer_id = Db::name('customer')->where('id','=',$request['customer_id'])->value('id');
            if (empty($customer_id)) {
                // code...
                $this->error = '当前客户不存在';
                return false;
            }
            $type            = isset($request['type']) ? intval($request['type']) : 0;
            if ($type == 0) {
                $this->error = '类型错误';
                return false;
            }else if ($type == 1) {// 更新进店时间
                // code...
                $saveData['new_join_shop_time']      = time();
            }else if ($type == 2) {// 更新转店状态
                // code...
                $saveData['turn_status']             = 2;
            }
            Db::name('customer')->where('id','=',$customer_id)->update($saveData);
            $this->error    = '更新成功';
            return true;
        } catch (\Exception $e) {
            $this->error    = '更新失败';
            return false;
        }
    }

    /**
     * 相册列表
     * @param  array $request 请求参数
     * @return bool
     */
    public function albumList(array $request): array
    {
        $customer_id = $request['customer_id'] ?? 0;

        $list = Db::name('customer_album')
                ->where('customer_id','=',$customer_id)
                ->where('is_del','=',0)
                ->select()
                ->toArray();
        $settingList    = Db::name('item_type')->column('name', 'id');

        $newList = [];
        foreach ($list as $key => $val){

            $newKey = $val['item_one'].'-'.$val['item_two'].'-'.$val['item_three'];
            if(!isset($newList[$newKey])){

                $caseWhere = [];

                array_push($caseWhere,['customer_id','=',$customer_id]);
                array_push($caseWhere,['item_one','=',$val['item_one']]);
                array_push($caseWhere,['item_two','=',$val['item_two']]);
                array_push($caseWhere,['item_three','=',$val['item_three']]);
                array_push($caseWhere,['selection_results','in',[1,2,3]]);

                $caseRes = Db::name('case')->where($caseWhere)->order('id DESC')->find();

                $newList[$newKey]['item_one_name'] = $settingList[$val['item_one']] ?? '';
                $newList[$newKey]['item_two_name'] = $settingList[$val['item_two']] ?? '';
                $newList[$newKey]['item_three_name'] = $settingList[$val['item_three']] ?? '';
                $newList[$newKey]['list'] = [];
                $newList[$newKey]['id']   = $val['id'];
                $newList[$newKey]['haveBtn'] = $caseRes['selection_results'] ?? 'null' ;
                $newList[$newKey]['caseId'] = $caseRes['id'] ?? '' ;
            }
            $one = [
                    'id'=>$val['id'],
                    'src'=>$val['src'],
                    'create_time'=>date('Y-m-d H:i:s',$val['create_time'])
                    ];
            array_push($newList[$newKey]['list'],$one);
            // array_push($newList[$newKey]['list'],[$val['src']]);
        }

        // exit;
        $newList = array_values($newList);
        return ['list'=>$newList];
    }

    /**
     * 新增相片
     * @param  array $request 请求参数
     * @return bool
     */
    public function addAlbum(array $request): bool
    {
        try{
            $addData['create_time']  = time();
            $addData['user_id']      = $request['user_id'] ?? '';
            $addData['shop_id']      = $request['shop_id'] ?? 0;
            $addData['customer_id']  = $request['customer_id'] ?? 0;
            $addData['item_one'] = $request['item_one'] ?? 0;
            $addData['item_two']      = $request['item_two'] ?? 0;
            $addData['item_three'] = $request['item_three'] ?? 0;

            if(empty($addData['item_one'])){
                $this->error = '请选择上传的照片的品项一级分类';
                return false;
            }
            if(empty($addData['item_two'])){
                $this->error = '请选择上传的照片的品项二级分类';
                return false;
            }
            if(empty($addData['item_three'])){
                $this->error = '请选择上传的照片的品项三级分类';
                return false;
            }
            $src = $request['src'] ?? '';
            if(is_array($src)){
                foreach ($src as $key => $val){
                    if(empty($src)){
                        $this->error = '请选择上传的照片';
                        return false;
                    }
                }
                foreach ($src as $key => $val){
                    $addData['src']          = $val;
                    $id = Db::name('customer_album')->insertGetId($addData);
                }
            }else{
                if(empty($src)){
                    $this->error = '请选择上传的照片';
                    return false;
                }
                $addData['src']          = $src;
                $id = Db::name('customer_album')->insertGetId($addData);
            }

            $this->error    = '添加成功';
            return true;
        } catch (\Exception $e) {
            $this->error    = '添加失败';
            return false;
        }
    }

    /**
     * 删除相片
     * @param  array $request 请求参数
     * @return bool
     */
    public function deleteAlbum(array $request): bool
    {
        try
        {
            $id = $request['id'] ?? 0;
            if (!$id) {
                $this->error = '请选择删除的照片';
                return false;
            }
            $user_id = $request['user_id'] ?? 0;
            if (!$user_id) {
                $this->error = '缺少必传参数-删除人ID';
                return false;
            }

            // 查询照片信息并验证权限
            $photo = Db::name('customer_album')
                ->where('id', $id)
                ->field('user_id, is_del')
                ->find();

            if (!$photo) {
                $this->error = '照片不存在或已被删除';
                return false;
            }

            // 检查是否已被删除
            if ($photo['is_del'] == 1) {
                $this->error = '照片已被删除';
                return false;
            }

            // 验证当前用户是否是照片添加人
            if ($photo['user_id'] != $user_id) {
                $this->error = '无权删除他人上传的照片';
                return false;
            }

            // 执行删除（逻辑删除）
            $result = Db::name('customer_album')
                ->where('id', $id)
                ->update([
                    'is_del' => 1,
                    'update_time' => time()
                ]);

            if ($result) {
                $this->error = '删除成功';
                return true;
            }

            $this->error = '删除失败';
            return false;
        } catch (\Exception $e) {
            $this->error = '删除失败：系统错误';
            return false;
        }
    }

    /**
     * 删除案例治疗记录照片
     * @param  array $request 请求参数
     * @return bool
     */
    public function deleteCaseLogImg(array $request): bool
    {

        try{
            $id = $request['id'] ?? 0;
            $key = $request['key'] ?? '';

            if(!$id){
                $this->error    = '请选择删除的照片';
                return false;
            }


            $tagLog = Db::name('case_log')->where('id','=',$id)->find();
            $images = explode(',',$tagLog['images']);

            unset($images[$key]);

            $newImages = implode(',',$images);

            Db::name('case_log')->where('id','=',$id)->update(['images' => $newImages]);

            $this->error    = '删除成功';
            return true;
        } catch (\Exception $e) {
            $this->error    = '删除失败';
            return false;
        }
    }

    /***
     * 客户余额的处理
     * $customer_id     客户的id
     * $balanceData [   余额变更数据集
     *     change_type     变动类型 1:增加 2:减少
     *     change_money    变更的本金
     *     complimentary_money  变更的赠金
     *     balance_category_id  变更的余额的类型 1:疤痕 2:项目
     * ]
     * $newOrderData[   新单变更数据集
     *      cj_time     成交时间-时间戳
     *      cj_money    成交金额
     *      cj_order_id 成交的订单单号
     * ]
     * $orderInfo[       本次需要新增的订单金额
     *      order_amount 本次订单金额
     *      order_time   本次订单的时间-时间戳
     * ]
     * $member_products  购买了几次会员商品
     * $yhjOrderInfo[    本次需要处理的优惠卷
     *      yhj_id       本次优惠卷的id
     *      order_id     本次订单的id
     *      operator_id  核销人的id
     * ]
     */
    public function processingFunds($customer_id=0,array $balanceData=array(),$deal_time=0,array $newOrderData=array(),$orderInfo = array(),$yhjOrderInfo = array()): bool
    {
            $customerInfo = Customer::find($customer_id);
            // 没有查询到客户的数据
            if (!$customerInfo) {
                throw new \Exception('顾客信息不存在');
            }

            if(!empty($balanceData)){
                $balanceInfo  = CustomerAccount::find($customer_id);
                //预存变更记录
                $accountLogModel = new CustomerAccountLog();
                $accountLogModels = clone $accountLogModel;

                $accountLogModels->customer_id =  $accountLogModel->customer_id = $orderInfo['customer_id'];
                $accountLogModels->order_id =  $accountLogModel->order_id = $orderInfo['order_id'];
                $accountLogModels->order_type =  $accountLogModel->order_type = $orderInfo['type'];
                $accountLogModels->symbol      =  $accountLogModel->symbol =  $balanceData['change_type'];// 1 增加 2减少
                $accountLogModels->create_time =  $accountLogModel->create_time = time();//创建时间
                $accountLogModels->notes       =  $accountLogModel->notes = $orderInfo['notes'];
                $accountLogModels->type       =  $accountLogModel->type = 1;
                $accountLogModels->remarks     =  $accountLogModel->remarks = $orderInfo['remarks'];

                $accountLogModel->last_amount = $balanceInfo['balance']; //修改之前的现金
                $accountLogModel->amount = $balanceData['change_balance'] ;//变动的金额
                $accountLogModel['type'] = 2;
                $accountLogModels->last_amount = $balanceInfo['gift']; //修改之前的赠金
                $accountLogModels->amount =  $balanceData['change_gift_balance'];//变动的金额
                $accountLogModels['type'] = 3;

                if($balanceData['change_type'] == 1){
                    $consumption = bcadd($customerInfo->consumption,$balanceData['change_balance'],2);  //最终累计消费金额
                    //收款、退款、收款作废 、退款作废方可处理以下信息
                    if(in_array($orderInfo['notes'],[703,704,705,706])){
                        //最终的累计消费本金
                        $balanceInfo->all_balance = bcadd($balanceInfo->all_balance,$balanceData['change_balance'],2);
                        //最终的累计消费赠金
                        $balanceInfo->all_gift = bcadd($balanceInfo->all_gift,$balanceData['change_gift_balance'],2);
                    }

                    //增加预存
                    $balanceInfo->balance = bcadd($balanceInfo->balance,$balanceData['change_balance'],2);
                    $balanceInfo->gift = bcadd($balanceInfo->gift,$balanceData['change_gift_balance'],2);

                }
                else if($balanceData['change_type'] == 2){
                    $consumption = bcsub($customerInfo->consumption,$balanceData['change_balance'],2); //最终累计消费金额
                    //收款、退款、收款作废 、退款作废方可处理以下信息
                    if(in_array($orderInfo['notes'],[703,704,705,706])){
                        //最终的累计消费本金
                        $balanceInfo->all_balance = bcsub($balanceInfo->all_balance,$balanceData['change_balance'],2);
                        //最终的累计消费赠金
                        $balanceInfo->all_gift = bcsub($balanceInfo->all_gift,$balanceData['change_gift_balance'],2);
                    }

                    //减少预存
                    $balanceInfo->balance = bcsub( $balanceInfo->balance,$balanceData['change_balance'],2);
                    $balanceInfo->gift = bcsub($balanceInfo->gift,$balanceData['change_gift_balance'],2);

                }


                $accountLogModel ->now_amount = $balanceInfo->balance; //变动后的本金
                $accountLogModels->now_amount = $balanceInfo->gift; //变动后的赠金


                //预存变更记录
                $balanceInfo->save();
                $accountLogModel->save();
                $accountLogModels->save();
            }

            if($orderInfo['notes'] == 703){
                // 新单的处理-收款单收款
                if($customerInfo['cj_time']==0 && !empty($newOrderData)){
                    $cj_time     = $newOrderData['cj_time'] ?? 0;
                    $cj_money    = $newOrderData['cj_money'] ?? 0;
                    $cj_order_id = $newOrderData['cj_order_id'] ?? 0;
                    if ($cj_time>0 && $cj_money>0 && $cj_order_id>0) {
                        // 新单数据的存储
                        $customerInfo->cj_time     = $cj_time;
                        $customerInfo->cj_money    = $cj_money;
                        $customerInfo->cj_order_id = $cj_order_id;
                    }
                }
            }

            //收款、退款、收款作废 、退款作废方可处理以下信息
            if(in_array($orderInfo['notes'],[703,704,705,706])){
               $customerInfo->consumption = $consumption;
                //处理顾客分类
                switch ($consumption){
                    case $consumption >= 50000:
                        //a类
                        $customerInfo->member_classification = 73; break;
                    case $consumption >= 15000:
                        //b类
                        $customerInfo->member_classification = 72; break;
                    case $consumption >= 5000:
                        //c类
                        $customerInfo->member_classification = 71; break;
                    case $consumption >= 1:
                        //e类
                        $customerInfo->member_classification = 70; break;
                    default:break;
                }

                if(time() <= $customerInfo->be_overdue_time){
                    // 处理客户应该是哪个级别的会员
                    $customerGradeList = CustomerGrade::cache(true,600)->select()->toArray();
                    $membership_leve = 0;
                    foreach($customerGradeList as $key => $val){
                        if ($val['maximum']==0 && $val['minimum']<= $consumption) {//当时最后一级时,大于初始金额即可设置为该等级
                            $membership_leve = $val['id'];
                        }else if($val['maximum']>=$consumption && $val['minimum']<=$consumption){
                            $membership_leve = $val['id'];
                        }
                    }
                    $customerInfo->membership_leve = $membership_leve;  //顾客会员等级
                }

            }

            $customerInfo->save();
        return true;
    }




    /**
     * 增加客户的服务
     */
    public function addCustomService($customer_id,$serviceDataAll):bool
    {
        try{
            $addAll = [];

            foreach($serviceDataAll as $key => $value){
                $addData['goods_alias_name'] = $value['goods_alias_name']??''; //商品别名
                $addData['order_goods_id'] = $value['order_goods_id']??0;
                $addData['order_id']    = $value['order_id'] ?? '';  //订单id
                $addData['name']    = $value['name'] ?? '';  //服务名称
                $addData['num']     = $value['num'] ?? 0;   // 必填--服务类型：1按期2按次
                $addData['shop_id'] = $value['shop_id'] ?? 0;    // 店铺id
                $addData['customer_id']  = $customer_id;   // 必填--客户id
                $addData['service_type'] = $value['service_type'] ?? 2;   // 必填--服务类型：1按期2按次
                $addData['start_time']   = $value['start_time'] ?? '';    // 类型为1是必填--服务开始时间
                $addData['end_time']     = $value['end_time'] ?? '';      // 类型为1是必填--服务开始时间
                $addData['experience']   = $value['experience'] ?? 0;     // 0否1是 是否体验
                $addData['kk_user_id']   = $value['kk_user_id'] ?? 0;     // 开卡人id
                $addData['kk_money']     = $value['kk_money'] ?? 0;       // 开卡金额
                $addData['create_time']  = time();     // 创建时间
                $addData['goods_id']     = $value['goods_id'] ?? 0;     //品项id
                $addData['category_id']  = $value['category_id'] ?? 0;      // 创建时间
                $addData['consume_store_transfer']  = $value['consume_store_transfer'] ?? 0;      // 消耗的店转
                $addData['consume_gratuity']  = $value['consume_gratuity'] ?? 0;      // 消耗的赠金
                $addData['consume_money']  = $value['consume_money'] ?? 0;      // 消耗的本金
                $addData['service_max_num']  = $value['service_max_num'] ?? 0;      // 总最高进店次数
                $addData['first_month_max_service_num']  = $value['first_month_max_service_num'] ?? 0;      // 首次
                $addData['middle_month_max_service_num']  = $value['middle_month_max_service_num'] ?? 0;      // 中间
                $addData['end_month_max_service_num']  = $value['end_month_max_service_num'] ?? 0;      // 结尾

                $addData['category_type_one']  = $value['category_type_one'] ?? 0;      // 品项的一级分类
                $addData['category_type_two']  = $value['category_type_two'] ?? 0;      // 品项的二级分类
                $addData['category_type_three']  = $value['category_type_three'] ?? 0;      //品项的三级分类

                $addData['real_cancel_balance']  = $value['real_cancel_balance'] ?? 0;      // 真实消耗的本金
                $addData['real_cancel_gift']  = $value['real_cancel_gift'] ?? 0;      //真实消耗赠金

                $addData['discount_amount']  = $value['discount_amount'] ?? 0;      //真实消耗赠金

                $addData['status'] = 1;
                if($addData['service_type'] == 1 && $addData['end_time']<=time()){
                    $addData['status'] = 2;
                }else{
                    if ($addData['num']==0) {
                        $addData['status'] = 1;
                    }
                }
                array_push($addAll,$addData);
            }
            $serviceModel = new Service();
            $res = $serviceModel->saveAll($addAll);
            return true;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    // 客户资料推送金蝶
    public function pushKingCustomer($customer_id): bool
    {

        $customerInfo = Db::name('customer')->where('id','=',$customer_id)->find();
        $shopInfo = Db::name('shop')->where('shop_id','=',$customerInfo['shop_id'])->find();

        if(!$customerInfo || !$shopInfo || $shopInfo['type'] == 2){
            $this->error    = '店铺客户数据异常';
            return false;
        }
        if(empty($shopInfo['market_kingdee_code']) || empty($shopInfo['keycode'])){
            $this->error    = '店铺金蝶编码异常';
            return false;
        }
        if(!empty($customerInfo['fcustId']) && !empty($customerInfo['king_no'])){
            $this->error    = '客户金蝶资料已存在';
            return true;
        }


        $kingData = [
            'king_no'       => $customerInfo['king_no'],
            'fcustId'       => $customerInfo['fcustId'] ?? 0,
            'customer_name' => $customerInfo['customer_name'],
            'sale_no'       => $shopInfo['market_kingdee_code'],
            'shop_no'       => $shopInfo['keycode'],
            'shop_id'       => $shopInfo['shop_id'],
            'customer_id'   => $customer_id,
        ];

        // 推送资料
        $kingdee = new \Kingdee\Kingdee();
        $res = $kingdee->add_customer($kingData);


        if ($res === true){
            // 提交客户资料
            $customerInfo = Db::name('customer')->where('id','=',$customer_id)->find();
            $subData = [
                    'fcustId'     => $customerInfo['fcustId'],
                    'customer_id' => $customer_id,
                ];
            $res = $kingdee->submit_customer($subData);
            if ($res !== true){
                $msg = $res === false?'客户资料推送失败':$res;
                $this->error = $msg;
                return false;
            }
            $auditData = [
                    'fcustId'     => $customerInfo['fcustId'],
                    'customer_id' => $customer_id,
                ];
            $res = $kingdee->audit_customer($auditData);
            if ($res !== true){
                $msg = $res === false?'客户资料推送失败':$res;
                $this->error = $msg;
                return false;
            }
            // 审核客户资料
            return true;
        }else{
            $msg = $res === false?'客户资料推送失败':$res;
            $this->error = $msg;
            return false;
        }
    }
    /**
     * 获取黄v数据
     */
    public function getYellowV($request):array
    {
        $staffIds = [550,945,1026];
        $shopId = '73782774881835';//中医院
        $staff = Db::name('admin_user')->field('id,realname')->where('id','in',$staffIds)->select()->toArray();
        $data = [];
        foreach($staff as $value)
        {
            $data[$value['id']]['name']=$value['realname'];
            $data[$value['id']]['id']=$value['id'];
        }
        $baseWhere = [];
        array_push($baseWhere,['a.operator','in',$staffIds]);
        array_push($baseWhere,['a.shop_id','=',$shopId]);
        array_push($baseWhere,['a.nurse_id','<>',0]);
        array_push($baseWhere,['a.create_time','>=',strtotime($request['start_time'])]);
        array_push($baseWhere,['a.create_time','<',strtotime($request['end_time'])+24*60*60]);
        $where = [];
        array_push($where,['b.consultation_status','=',2]);
        //预约线上
        $reservationConsultation = Db::name('customer')->alias('a')
            ->join('customer_extra b','a.id = b.customer_id','left')
            ->field('a.operator as operator_id,count(*) as count')
            ->where($baseWhere)
            ->where($where)
            ->group('a.operator')
            ->select()->toArray();


        $where = [];
        array_push($where,['b.consultation_status','=',1]);
        //预约到院
        $reservationReach = Db::name('customer')->alias('a')
            ->join('customer_extra b','a.id = b.customer_id','left')
            ->field('a.operator as operator_id,count(*) as count')
            ->where($baseWhere)
            ->where($where)
            ->group('a.operator')
            ->select()->toArray();

        foreach($reservationConsultation as $value)
        {
            $data[$value['operator_id']]['reservationConsultation']=$value['count'];
            $data[$value['operator_id']]['id']=$value['operator_id'];
        }
        foreach($reservationReach as $value)
        {
            $data[$value['operator_id']]['reservationReach']=$value['count'];
        }

        $baseWhere2 = [];
        array_push($baseWhere2,['a.operator','in',$staffIds]);
        array_push($baseWhere2,['a.shop_id','=',$shopId]);
        array_push($baseWhere2,['a.nurse_id','<>',0]);


        $where = [];
        array_push($where,['b.consultation_status','=',2]);
        $orWhere=[];
        array_push($orWhere,['b.reach_first_time','between',[strtotime($request['start_time']),strtotime($request['end_time'])+24*60*60]]);
        array_push($orWhere,['b.reach_second_time','between',[strtotime($request['start_time']),strtotime($request['end_time'])+24*60*60]]);
        //实际线上
        $realReservationConsultation = Db::name('customer')->alias('a')
            ->join('customer_extra b','a.id = b.customer_id','left')
            ->field('a.operator as operator_id,count(*) as count')
            ->where($where)
            ->where($baseWhere2)
            ->where(function($query)use($orWhere){
                $query->whereOr($orWhere);
            })
            ->group('a.operator')
            ->select()->toArray();

        $where = [];
        array_push($where,['b.consultation_status','=',1]);
        $orWhere=[];
        array_push($orWhere,['b.consultation_first_time','between',[strtotime($request['start_time']),strtotime($request['end_time'])+24*60*60]]);
        array_push($orWhere,['b.consultation_second_time','between',[strtotime($request['start_time']),strtotime($request['end_time'])+24*60*60]]);
        //实际到院
        $realReservationReach = Db::name('customer')->alias('a')
            ->join('customer_extra b','a.id = b.customer_id','left')
            ->field('a.operator as operator_id,count(*) as count')
            ->where($where)
            ->where($baseWhere2)
            ->whereOr(function($query)use($orWhere){
                $query->whereOr($orWhere);
            })
            ->group('a.operator')
            ->select()->toArray();


        foreach($realReservationConsultation as $value)
        {
            $data[$value['operator_id']]['realReservationConsultation']=$value['count'];
        }
        foreach($realReservationReach as $value)
        {
            $data[$value['operator_id']]['realReservationReach']=$value['count'];
        }
        // print_r($data);
        // exit;
        // $data['reservationSum'] = $data['reservationConsultation']+$data['reservationReach'];

        $where = [];
        array_push($baseWhere2,['c.status','=',2]);
        array_push($baseWhere2,['c.type','=',3]);
        array_push($baseWhere2,['c.deal_time','>=',strtotime($request['start_time'])]);
        array_push($baseWhere2,['c.deal_time','<',strtotime($request['end_time'])+24*60*60]);


        array_push($where,['b.consultation_status','=',2]);
        array_push($where,['c.order_type','=',1]);
        //看诊成交
        $dealConsultation = $this->reckon(array_merge($where,$baseWhere2),'a.operator as operator_id,count(distinct uid) as count');


        $where = [];
        array_push($where,['b.consultation_status','=',1]);
        array_push($where,['c.order_type','=',1]);
        //到院成交
        $dealReach = $this->reckon(array_merge($where,$baseWhere2),'a.operator as operator_id,count(distinct uid) as count');

        foreach($dealConsultation as $value)
        {
            $data[$value['operator_id']]['dealConsultation']=$value['count'];
        }
        foreach($dealReach as $value)
        {
            $data[$value['operator_id']]['dealReach']=$value['count'];
        }


        $where = [];
        array_push($where,['b.consultation_status','=',2]);
        array_push($where,['c.order_type','=',1]);
        //线上成交新单金额
        $dealConsultationNew = $this->reckon(array_merge($where,$baseWhere2),'a.operator as operator_id,sum(pay_amount) as sum');
        $where = [];
        array_push($where,['b.consultation_status','=',1]);
        array_push($where,['c.order_type','=',1]);
        //到院成交新单金额
        $dealReachNew = $this->reckon(array_merge($where,$baseWhere2),'a.operator as operator_id,sum(pay_amount) as sum');

        foreach($dealConsultationNew as $value)
        {
            $data[$value['operator_id']]['dealConsultationNew']=$value['sum'];
        }
        foreach($dealReachNew as $value)
        {
            $data[$value['operator_id']]['dealReachNew']=$value['sum'];
        }


        $where = [];
        array_push($where,['b.consultation_status','=',2]);
        array_push($where,['c.order_type','=',2]);
        //线上成交补单金额
        $dealConsultationOld = $this->reckon(array_merge($where,$baseWhere2),'a.operator as operator_id,sum(pay_amount) as sum');

        $where = [];
        array_push($where,['b.consultation_status','=',1]);
        array_push($where,['c.order_type','=',2]);
        //到院成交补单金额
        $dealReachOld = $this->reckon(array_merge($where,$baseWhere2),'a.operator as operator_id,sum(pay_amount) as sum');

        foreach($dealConsultationOld as $value)
        {
            $data[$value['operator_id']]['dealConsultationOld']=$value['sum'];
        }
        foreach($dealReachOld as $value)
        {
            $data[$value['operator_id']]['dealReachOld']=$value['sum'];
        }
        // print_r($data);
        // exit;
        foreach($data as $key => $value)
        {
            if(empty($value['id']))
                {
                    unset($data[$key]);
                    continue;
                }
            if(empty($value['realReservationConsultation']))
                $data[$key]['realReservationConsultation']=0;
            if(empty($value['realReservationReach']))
                $data[$key]['realReservationReach']=0;

            if(empty($value['dealConsultation']))
                $data[$key]['dealConsultation']=0;
            if(empty($value['dealReach']))
                $data[$key]['dealReach']=0;

            if(empty($value['reservationConsultation']))
            {
                $data[$key]['reservationConsultation']=0;
                $data[$key]['reservationConsultationRate']=0;
            }else{
                $data[$key]['reservationConsultationRate']=number_format($data[$key]['dealConsultation']/$data[$key]['reservationConsultation'], 2)*100;
            }
            $data[$key]['reservationConsultationRate'].='%';
            if(empty($value['reservationReach']))
            {
                $data[$key]['reservationReach']=0;
                $data[$key]['reservationReachRate']=0;
            }else{
                $data[$key]['reservationReachRate']=number_format($data[$key]['dealReach']/$data[$key]['reservationReach'], 2)*100;
            }
            $data[$key]['reservationReachRate'].='%';
            $data[$key]['reservationSum'] = $data[$key]['reservationConsultation']+$data[$key]['reservationReach'];
            if(empty($value['reservationConsultation'])&&empty($value['reservationReach']))
            {
                $data[$key]['sumRate']=0;
            }else{
                $data[$key]['sumRate']=number_format(($data[$key]['dealConsultation']+$data[$key]['dealReach'])/($data[$key]['reservationConsultation']+$data[$key]['reservationReach']), 2)*100;
            }
            $data[$key]['sumRate'].='%';
            if(empty($value['dealConsultationNew']))
                $data[$key]['dealConsultationNew']=0;
            if(empty($value['dealReachNew']))
                $data[$key]['dealReachNew']=0;
            if(empty($value['dealConsultationOld']))
                $data[$key]['dealConsultationOld']=0;
            if(empty($value['dealReachOld']))
                $data[$key]['dealReachOld']=0;
            $data[$key]['newSum']=$data[$key]['dealConsultationNew']+$data[$key]['dealReachNew'];
            $data[$key]['oldSum']=$data[$key]['dealConsultationOld']+$data[$key]['dealReachOld'];
            $data[$key]['sum']=number_format($data[$key]['newSum']+$data[$key]['oldSum'],2);
        }
        $data = array_merge($data,[]);
        // print_r($data);
        // exit;
        return $data;

    }

    /**
     * 黄v客服详情页数据
     */
    public function getYellowVService($request)
    {
        $staffId = $request['id'];
        $staffIds = [550,945,1026];
        $shopId = '73782774881835';//中医院
        $where = [];
        array_push($where,['a.operator','=',$staffId]);
        array_push($where,['c.consultation_status','in',[1,2]]);
        array_push($where,['a.nurse_id','<>',0]);
        array_push($where,['a.create_time','>',strtotime($request['start_time'])]);
        array_push($where,['a.create_time','<',strtotime($request['end_time'])+24*60*60]);
        $data = Db::name('customer')->alias('a')
        ->join('shop_person b','b.id = a.nurse_id','left')
        ->join('customer_extra c','c.customer_id = a.id','left')
        ->field('c.consultation_status,b.id,b.name,count(*) as count')
        ->where($where)->group('a.nurse_id,c.consultation_status')->select()->toArray();
        $where = [];
        array_push($where,['a.operator','in',$staffIds]);
        array_push($where,['a.nurse_id','<>',0]);
        array_push($where,['a.shop_id','=',$shopId]);
        array_push($where,['c.consultation_status','in',[1,2]]);
        // array_push($where,['b.position_id','in',[8,9,10]]);
        $physician = Db::name('customer')->alias('a')
        ->join('shop_person b','b.id = a.nurse_id','right')
        ->join('customer_extra c','c.customer_id = a.id','left')
        ->field('b.id,b.name')
        ->where($where)->group('a.nurse_id')->select()->toArray();
        $dataTwo=[];
        foreach($data as $value)
        {
            $dataTwo[$value['id']][$value['consultation_status']]=$value;
        }
        $result = [];
        foreach($physician as $key=>$value)
        {
            $result[$key]['consultation'] = $dataTwo[$value['id']][1]['count']??0;
            $result[$key]['reach'] = $dataTwo[$value['id']][2]['count']??0;
            $result[$key]['name'] = $value['name'];
            $result[$key]['sum'] = $result[$key]['consultation']+$result[$key]['reach'];
        }
        return $result;
    }
    /**
     * 黄v护理师详情页
     */
    public function getYellowVPhysician($request):array
    {
        $staffId = $request['id'];
        // $staffIds = [550,945,940];
        $consultation_status = $request['consultation_status'];
        $shopId = '73782774881835';//中医院
        $where = [];
        array_push($where,['a.operator','=',$staffId]);
        array_push($where,['a.nurse_id','<>',0]);
        array_push($where,['a.shop_id','=',$shopId]);
        array_push($where,['c.consultation_status','in',[1,2]]);
        // array_push($where,['b.position_id','in',[8,9]]);
        $physician = Db::name('customer')->alias('a')
            ->join('shop_person b','b.id = a.nurse_id','right')
            ->join('customer_extra c','c.customer_id = a.id','left')
            ->field('b.id,b.name')
            ->where($where)->group('a.nurse_id')->select()->toArray();
        $where = [];
        array_push($where,['a.operator','=',$staffId]);
        array_push($where,['a.nurse_id','<>',0]);
        array_push($where,['b.consultation_status','=',$consultation_status]);
        array_push($where,['a.create_time','>',strtotime($request['start_time'])]);
        array_push($where,['a.create_time','<',strtotime($request['end_time'])+24*60*60]);

        $number = Db::name('customer')->alias('a')
            ->join('customer_extra b','b.customer_id = a.id','left')
            ->field('a.nurse_id,count(*) as count')
            ->where($where)
            ->group('a.nurse_id')->select()->toArray();
        array_push($where,['c.status','=',2]);
        array_push($where,['c.type','=',3]);

        $deal = Db::name('customer')->alias('a')
            ->join('customer_extra b','a.id = b.customer_id','left')
            ->join('shop_refund_order c','c.uid = b.customer_id','left')
            ->field('a.nurse_id,count(distinct uid) as count')
            ->where($where)
            ->group('a.nurse_id')->select()->toArray();

        $dealMoney = Db::name('customer')->alias('a')
            ->join('customer_extra b','a.id = b.customer_id','left')
            ->join('shop_refund_order c','c.uid = b.customer_id','left')
            ->field('a.nurse_id,sum(pay_amount) as sum')
            ->where($where)
            ->group('a.nurse_id')->select()->toArray();
        $numberData=[];
        foreach($number as $value)
        {
            $numberData[$value['nurse_id']]=$value['count'];
        }
        $dealData=[];
        foreach($deal as $value)
        {
            $dealData[$value['nurse_id']]=$value['count'];
        }
        $dealMoneyData=[];
        foreach($dealMoney as $value)
        {
            $dealMoneyData[$value['nurse_id']]=$value['sum'];
        }
        $result = [];
        foreach($physician as $key =>$value)
        {
            $result[$key]['name']=$value['name'];
            if(empty($numberData[$value['id']]))
            {
                $result[$key]['number'] = 0;
            }else{
                $result[$key]['number'] = $numberData[$value['id']];
            }
            if(empty($dealData[$value['id']]))
            {
                $result[$key]['deal'] = 0;
            }else{
                $result[$key]['deal'] = $dealData[$value['id']];
            }
            if(empty($dealMoneyData[$value['id']]))
            {
                $result[$key]['dealMoney'] = 0;
            }else{
                $result[$key]['dealMoney'] = $dealMoneyData[$value['id']];
            }
            if(empty($result[$key]['number']))
            {
                $result[$key]['dealRate']=0;
            }else{
                $result[$key]['dealRate']=number_format($result[$key]['deal']/$result[$key]['number'],2);
            }
            if(empty($result[$key]['deal']))
            {
                $result[$key]['avg']=0;
            }else{
                $result[$key]['avg']=number_format($result[$key]['dealMoney']/$result[$key]['deal'],2);
            }

        }
        return $result;

    }
    /**
     * sql统一处理
     */
    public function reckon($where,$field)
    {
        return Db::name('customer')->alias('a')
        ->join('customer_extra b','a.id = b.customer_id','left')
        ->join('shop_refund_order c','c.uid = b.customer_id','left')
        ->field($field)
        ->where($where)
        ->group('a.operator')
        ->select()->toArray();
    }

    /**
     * 发送短信
     */
    public function sendMsg($data){
        $time = $data['time']?? '';
        $group   = $data['group'] ?? '';
        $money =  $data['money'] ?? '';
        $amount   = $data['amount'] ?? '';
        $params = [
            'apikey' => '9616eb7d8bd7ff79ca24af3fad8f192b',
            'mobile' => $data['phone'],
            'tpl_id' => $data['template_id'],
            'tpl_value' =>('#time#').'='.$time.'&'.('#group#').'='.$group.'&'.('#money#').'='.$money.'&'.('#amount#').'='.$amount
        ];
        $market_id = 0;
        $shop_id = isset($data['shop_id'])?$data['shop_id']:0;
        if($shop_id>0){
            $market_id = DB::name('shop')->where('shop_id',$shop_id)->value('market_id');
        }
        $data['send_status'] = 0;
        if($data['is_send'] == 1 && in_array($market_id,[8,9,10,11,105])){
//        if($data['is_send'] == 1 && $data['customer_id'] == 594774){
            $sendmsgData = $this->sendSms($params);
            $sendmsgData =json_decode($sendmsgData,1);
            $data['send_status'] = $sendmsgData['code'] == 0?1:0;
        }
        $this->addSendmsgLog($data);
    }
    /**
     * 发送短信记录
     */
    public function addSendmsgLog($data){
        $insert =[
            'template_id'=>isset($data['template_id'])?$data['template_id']:0,
            'shop_id'=>isset($data['shop_id'])?$data['shop_id']:0,
            'customer_id'=>isset($data['customer_id'])?$data['customer_id']:0,
            'order_id'=>isset($data['order_id'])?$data['order_id']:0,
            'order_type'=>isset($data['order_type'])?$data['order_type']:0,
            'residue_amount'=>isset($data['residue_amount'])?$data['residue_amount']:0,
            'consumption_amount'=>isset($data['consumption_amount'])?$data['consumption_amount']:0,
            'send_status'=>isset($data['send_status'])?$data['send_status']:0,
            'is_send'=>isset($data['is_send'])?$data['is_send']:0,
            'phone'=>isset($data['phone'])?$data['phone']:0,
            'create_time'=>time(),
        ];
        DB::name('sendmsg_log')->insert($insert);
    }

    function send_post($url, $post_data){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        /**配置返回信息**/
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//获取的信息以文件流的形式返回，不直接输出
        curl_setopt($curl, CURLOPT_HEADER, 0);//不返回header部分
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE); //禁止 cURL 验证对等证书
        curl_setopt($curl, CURLOPT_POST, 1); //支持post提交数据
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        $code = 200; //执行成功
        $data = curl_exec($curl);
        //捕抓异常
        if (curl_errno($curl)) {
            $code = 400; //执行异常
            $data = curl_error($curl);
        }
        curl_close($curl);
        return $data;
        // return array('code' => $code, 'data' => json_decode($data, true));
    }
    //发送短信动作
    public function sendSms($params)
    {
        $param = '';
        foreach($params as $key => $val){
            $param .= urlencode($key).'='.urlencode($val).'&';
        }
        $param = substr($param,0,strlen($param)-1);
        $a = $this->send_post("https://sms.yunpian.com/v2/sms/tpl_single_send.json", $param);
        return $a;
    }

    public function getCustomerBalanceSum($customer_id,$shop_id){
        $map =[
            ['customer_id','=',$customer_id],
            ['shop_id','=',$shop_id],
        ];
        $balanceList = Db::name('customer_balance')
            ->where($map)
            ->field('money,complimentary_money,shop_transfer_money')->select()->toArray();
        $amount_sum = [];
        foreach($balanceList as $k=>$v){
            array_push($amount_sum,$v['money']);
            array_push($amount_sum,$v['complimentary_money']);
            array_push($amount_sum,$v['shop_transfer_money']);
        }
        return array_sum($amount_sum);
    }


    // 手机号变更记录
    public function getPhoneChangeLog($param)
    {
        $page = $param['page'] ?? 1;
        $pagesize = $param['pagesize'] ?? 10;
        if(empty($param['customer_id']))
        {
             $this->error = "用户ID不能为空";
            return false;
        }
        $res = [];

        $res = Db::name('customer_info_change_log')
        ->field([
            'l.id',
            'l.last_customer_phone',
            'l.telephone',
            "FROM_UNIXTIME(l.create_time, '%Y-%m-%d %H:%i:%s') as create_time", // 转换时间戳
            'a.realname',
            'c.customer_name'
        ])
        ->alias('l')
        ->where('l.customer_id', $param['customer_id'])
        ->join('customer c', 'c.id = l.customer_id')
        ->join('admin_user a', 'a.id = l.operator_id')
        ->paginate([
            'list_rows'=>$pagesize,
            'page'=>$page,
            'query'=>request()->param()
        ]);
        $res = json_decode(json_encode($res),true);
        return $res;
    }


    //主治医师+所属护士变更记录
    public function getChangeLogList($param)
    {
        $page = $param['page'] ?? 1;
        $pagesize = $param['pagesize'] ?? 10;
        $where = [];
        if(empty($param['customer_id']))
        {
             $this->error = "用户ID不能为空";
            return false;
        }else
        {
            $where[] = ['l.customer_id','=',$param['customer_id']];
        }
        if(!empty($param['type']))
        {
            $where[] = ['l.type','=',$param['type']];
        }
        $res = [];

        $res = Db::name('customer_change_log')
            ->field([
            'l.id',
            'l.shop_id',
            'l.customer_id',
            'l.type',
            'l.last',
            'l.now',
            "FROM_UNIXTIME(l.create_time, '%Y-%m-%d %H:%i:%s') as create_time", // 时间戳转日期
            'a.realname',
            'c.customer_name',
            'pl.name as last_name',
            'pn.name as now_name'
        ])
        ->alias('l')
        ->where($where)
        ->join('customer c', 'c.id = l.customer_id')
        ->join('admin_user a', 'a.id = l.operator_id')
        ->join('shop_person pl', 'pl.id = l.last')
        ->join('shop_person pn', 'pn.id = l.now')
        ->paginate([
            'list_rows'=>$pagesize,
            'page'=>$page,
            'query'=>request()->param()
        ]);
        $res = json_decode(json_encode($res),true);
        return $res;

    }


    //统计有哪些营销中心转店的用户没有补充资料
    public function getTransferList($param)
    {
        $where = [];
        if(!empty($param['shopIds']))
        {
            $where[] = ['shop','in',$param['shopIds']];
        }

        $res = [];
        $string = '';
        $res = Db::name('customer')->where($where)->where('is_transfer',1)->column('customer_name,telephone');
        if(!empty($res))
        {
            $res = array_map(function($item)
            {
                return $item['customer_name'] . ' - ' . $item['telephone'];
            }, $res);
        }

        return $res;
    }


    // 用户账户列表
    public function getAccountInfo($param)
    {
        $page = $param['page'] ?? 1;
        $pagesize = $param['pagesize'] ?? 10;

        if(empty($param['customer_id']))
        {
             $this->error = "用户ID不能为空";
            return false;
        }
        $res = [];
        // 账户信息
        $account = Db::name('customer_account')->where('id',$param['customer_id'])->find();
        $res['account'] = $account;
        // 卡项
        // 优惠券
    }




}
